package model

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	"kubeInstall/utils"
)

type HostInfo struct {
	Cpu       int    `json:"cpu"`
	Memory    int    `json:"memory"`
	OsVersion string `json:"os_version"`
	Status    bool   `json:"status"`
}

type Host struct {
	ID   string `json:"id" gorm:"primary_key;column:host_id"`
	Name string `json:"name"`
	IP   string `json:"ip"`
	Port int    `json:"port"`
	//HostCredential string `json:"host_credential"`
	HostName string `json:"host_name"`

	CredentialType string `json:"credential_type"`
	// Credential content
	CredentialData string `json:"credential_data"`
	Username       string `json:"username"`

	Used bool `json:"used"`
	//master or node
	Role      string `json:"role"`
	ClusterId string `json:"cluster_id"`

	BaseModel
}

func (h *Host) Get(hostId string) (Host, error) {
	var host Host
	err := db.Where("host_id = ?", hostId).First(&host).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return host, fmt.Errorf("host ID %s not found", hostId)
		}
		return host, err
	}

	return host, nil
}

func (h *Host) GetHostRoleByClusterId(clusterId string, role string) ([]Host, error) {
	var hostList []Host

	err := db.Select("*").Where("cluster_id = ?&& role = ?", clusterId, role).Find(&hostList).Error

	if err != nil {
		return hostList, err
	}

	return hostList, nil
}

func (h *Host) List(limit, Offset int) ([]Host, error) {
	var hostList []Host
	if limit == 0 {
		limit = 10
	}
	err := db.Select("*").Limit(limit).Offset((Offset - 1) * limit).Find(&hostList).Error

	if err != nil {
		return hostList, err
	}

	return hostList, nil
}

func (h *Host) Create() (Host, error) {
	//判断host是否存在
	var count int

	db.Model(Host{}).Where("ip = ?&& port = ?", h.IP, h.Port).Count(&count)
	if count > 0 {
		return Host{}, errors.New("ip和端口已经存在！")
	}

	// 判断凭证信息是否合法
	//db.Model(Credential{}).Where("name = ?", h.HostCredential).Count(&count)

	//if count == 0 {
	//	return Host{}, errors.New("凭证信息不合法！")
	//}

	//插入数据，并返回。
	h.ID = utils.GenUUID()
	if err := db.Create(&h).Error; err != nil {
		return Host{}, err
	}
	return *h, nil
}

func (h *Host) Delete(hostId string) error {
	var host Host
	err := db.Where("host_id = ?", hostId).Delete(&host).Error

	return err
}

func (h *Host) Update(hostId string) error {
	var host Host
	err := db.Where("host_id = ?", hostId).Update(&host).Error
	return err
}
